package com.huawei.appgallery.jsonkit.api;

import androidx.annotation.NonNull;
import com.huawei.appgallery.jsonkit.api.annotation.FieldPrint;
import com.huawei.appgallery.jsonkit.api.annotation.FieldSecurity;
import com.huawei.appgallery.jsonkit.api.annotation.PrintLevel;
import com.huawei.appgallery.jsonkit.api.annotation.SecurityLevel;
import com.huawei.appgallery.jsonkit.impl.db.JsonBeanProcess;
import com.huawei.appmarket.service.activitydispatcher.OpenGateway.Param;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import o.blz;
import o.clq;
import o.dob;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public abstract class JsonBean {
    private static final char COMMA = ',';
    private static final String END_FLAG = "_";
    private static final int END_FLAG_LENGTH = "_".length();
    private static final String TAG = JsonBean.class.getSimpleName();

    enum e {
        CAN,
        IGONRE,
        CANNOT
    }

    static {
        blz.ˏ(JsonBean.class, new JsonBeanProcess());
    }

    public static boolean isFieldCanPrint(Field field) {
        return e.CANNOT != getFieldPrintType(field);
    }

    private static e getFieldPrintType(Field field) {
        e eVar = e.IGONRE;
        Annotation[] declaredAnnotations = field.getDeclaredAnnotations();
        if (declaredAnnotations != null && declaredAnnotations.length >= 1) {
            int length = declaredAnnotations.length;
            int i = 0;
            while (i < length) {
                Annotation annotation = declaredAnnotations[i];
                e eVar2 = annotation instanceof FieldPrint ? ((FieldPrint) annotation).print() == PrintLevel.PRINTABLE ? e.CAN : e.CANNOT : eVar;
                i++;
                eVar = eVar2;
            }
        }
        return eVar;
    }

    public static boolean isFieldPrivacy(Field field) {
        Annotation[] declaredAnnotations = field.getDeclaredAnnotations();
        if (declaredAnnotations == null || declaredAnnotations.length < 1) {
            return false;
        }
        for (Annotation annotation : declaredAnnotations) {
            if ((annotation instanceof FieldSecurity) && ((FieldSecurity) annotation).security() == SecurityLevel.PRIVACY) {
                return true;
            }
        }
        return false;
    }

    public void toJson(StringBuilder stringBuilder) throws IllegalAccessException, IllegalArgumentException {
        Field[] ˊ = dob.ˊ(getClass());
        if (ˊ.length > 0) {
            stringBuilder.append("{");
            for (Field field : ˊ) {
                field.setAccessible(true);
                String name = field.getName();
                if (name != null && name.endsWith("_")) {
                    name = name.substring(0, name.length() - END_FLAG_LENGTH);
                    Object obj = field.get(this);
                    if (obj != null) {
                        stringBuilder.append("\"").append(name).append("\":");
                        valueToJson(stringBuilder, obj, false);
                        stringBuilder.append(COMMA);
                    }
                }
            }
            formatJsonStr(stringBuilder);
            stringBuilder.append("}");
        }
    }

    public String toJson() throws IllegalAccessException, IllegalArgumentException {
        StringBuilder stringBuilder = new StringBuilder(WXMediaMessage.TITLE_LENGTH_LIMIT);
        toJson(stringBuilder);
        return stringBuilder.toString();
    }

    private void valueToJson(@NonNull StringBuilder stringBuilder, @NonNull Object obj, boolean z) throws IllegalAccessException, IllegalArgumentException {
        if (obj instanceof String) {
            stringBuilder.append(JSONObject.quote(obj.toString()));
        } else if ((obj instanceof Integer) || (obj instanceof Long) || (obj instanceof Boolean) || (obj instanceof Float) || (obj instanceof Byte) || (obj instanceof Character) || (obj instanceof Double) || (obj instanceof Short)) {
            stringBuilder.append(String.valueOf(obj));
        } else if (obj instanceof JsonBean) {
            appendJsonBean(stringBuilder, (JsonBean) obj, z);
        } else if (obj instanceof List) {
            listToJson(stringBuilder, (List) obj, z);
        } else if (obj instanceof Map) {
            mapToJson(stringBuilder, (Map) obj, z);
        } else if (obj.getClass().isArray()) {
            arrayToJson(stringBuilder, obj, z);
        } else if (obj instanceof JSONObject) {
            stringBuilder.append(((JSONObject) obj).toString());
        }
    }

    private void appendJsonBean(StringBuilder stringBuilder, JsonBean jsonBean, boolean z) throws IllegalAccessException {
        if (z) {
            jsonBean.toFilterJson(stringBuilder);
        } else {
            jsonBean.toJson(stringBuilder);
        }
    }

    private void listToJson(StringBuilder stringBuilder, List list, boolean z) throws IllegalAccessException, IllegalArgumentException {
        int size = list.size();
        if (size <= 0) {
            stringBuilder.append("[]");
            return;
        }
        stringBuilder.append("[");
        for (int i = 0; i < size; i++) {
            Object obj = list.get(i);
            if (obj != null) {
                valueToJson(stringBuilder, obj, z);
                stringBuilder.append(COMMA);
            }
        }
        formatJsonStr(stringBuilder);
        stringBuilder.append("]");
    }

    private void arrayToJson(StringBuilder stringBuilder, Object obj, boolean z) throws IllegalAccessException, IllegalArgumentException {
        int length = Array.getLength(obj);
        if (length <= 0) {
            stringBuilder.append("[]");
            return;
        }
        stringBuilder.append("[");
        for (int i = 0; i < length; i++) {
            Object obj2 = Array.get(obj, i);
            if (obj2 != null) {
                valueToJson(stringBuilder, obj2, z);
                stringBuilder.append(COMMA);
            }
        }
        formatJsonStr(stringBuilder);
        stringBuilder.append("]");
    }

    private void mapToJson(StringBuilder stringBuilder, Map map, boolean z) throws IllegalAccessException, IllegalArgumentException {
        if (map.size() <= 0) {
            stringBuilder.append("{}");
            return;
        }
        stringBuilder.append("{");
        Iterator it = map.entrySet().iterator();
        while (true) {
            Entry entry = (Entry) it.next();
            String str = (String) entry.getKey();
            Object value = entry.getValue();
            if (value != null) {
                stringBuilder.append("\"").append(str).append("\":");
                valueToJson(stringBuilder, value, z);
            }
            if (it.hasNext()) {
                stringBuilder.append(COMMA);
            } else {
                stringBuilder.append("}");
                return;
            }
        }
    }

    private void formatJsonStr(StringBuilder stringBuilder) {
        int length = stringBuilder.length();
        if (length > 0 && stringBuilder.charAt(length - 1) == COMMA) {
            stringBuilder.delete(length - 1, length);
        }
    }

    public void fromJson(JSONObject jSONObject) throws IllegalArgumentException, IllegalAccessException, InstantiationException, ClassNotFoundException, JSONException {
        Field[] ˊ = dob.ˊ(getClass());
        Object obj = null;
        for (int i = 0; i < ˊ.length; i++) {
            Field field = ˊ[i];
            field.setAccessible(true);
            String name = field.getName();
            if (name.endsWith("_")) {
                String substring = name.substring(0, name.length() - END_FLAG_LENGTH);
                if (jSONObject.has(substring)) {
                    Object obj2 = jSONObject.get(substring);
                    if (!JSONObject.NULL.equals(obj2)) {
                        try {
                            obj = valueFromJson(field.getType(), dob.ˎ(field), obj2);
                            ˊ[i].set(this, obj);
                        } catch (Throwable e) {
                            clq.ˎ.ˊ(TAG, getClass().getName() + ".fromJson error, fieldName:" + substring, e);
                            processValueError(field, obj);
                        } catch (Throwable e2) {
                            clq.ˎ.ˊ(TAG, getClass().getName() + ".fromJson error, fieldName:" + substring, e2);
                            processValueError(field, obj);
                        } catch (Throwable e22) {
                            clq.ˎ.ˊ(TAG, getClass().getName() + ".fromJson error, fieldName:" + substring, e22);
                            processValueError(field, obj);
                        } catch (Throwable e222) {
                            clq.ˎ.ˊ(TAG, getClass().getName() + ".fromJson error, fieldName:" + substring, e222);
                            processValueError(field, obj);
                        } catch (JSONException e3) {
                            clq.ˎ.ˊ(TAG, getClass().getName() + ".fromJson error, fieldName:" + substring + " :JSONException");
                            processValueError(field, obj);
                        }
                    }
                }
            }
        }
    }

    public String getSafeData() {
        String str = null;
        try {
            StringBuilder stringBuilder = new StringBuilder(WXMediaMessage.TITLE_LENGTH_LIMIT);
            toFilterJson(stringBuilder);
            str = stringBuilder.toString();
        } catch (IllegalAccessException e) {
            clq.ˎ.ˊ(TAG, "safe data to json error");
        } catch (IllegalArgumentException e2) {
            clq.ˎ.ˊ(TAG, "safe data to json error");
        }
        return str;
    }

    public void toFilterJson(StringBuilder stringBuilder) throws IllegalAccessException, IllegalArgumentException {
        Field[] ˊ = dob.ˊ(getClass());
        if (ˊ.length > 0) {
            stringBuilder.append("{");
            for (Field field : ˊ) {
                field.setAccessible(true);
                String name = field.getName();
                if (name != null && (name.endsWith("_") || getFieldPrintType(field) == e.CAN)) {
                    if (name.endsWith("_")) {
                        name = name.substring(0, name.length() - END_FLAG_LENGTH);
                    }
                    Object obj = field.get(this);
                    if (isFieldPrivacy(field)) {
                        stringBuilder.append("\"").append(name).append("\":").append("****").append(COMMA);
                    } else if (getFieldPrintType(field) == e.CANNOT) {
                        stringBuilder.append("\"").append(name).append("\":\"").append("*").append("\"").append(COMMA);
                    } else if (obj != null) {
                        stringBuilder.append("\"").append(name).append("\":");
                        valueToJson(stringBuilder, obj, true);
                        stringBuilder.append(COMMA);
                    }
                }
            }
            formatJsonStr(stringBuilder);
            stringBuilder.append("}");
        }
    }

    private void processValueError(Field field, Object obj) {
        if (obj != null && (obj instanceof String)) {
            try {
                Class type = field.getType();
                if (type.isPrimitive()) {
                    String name = type.getName();
                    if (Param.TYPE_INT.equals(name)) {
                        field.set(this, Integer.valueOf(Integer.parseInt((String) obj)));
                    } else if (Param.TYPE_FLOAT.equals(name)) {
                        field.set(this, Float.valueOf(Float.parseFloat((String) obj)));
                    } else if (Param.TYPE_LONG.equals(name)) {
                        field.set(this, Long.valueOf(Long.parseLong((String) obj)));
                    } else if (Param.TYPE_BOOLEAN.equals(name)) {
                        field.set(this, Boolean.valueOf(Boolean.parseBoolean((String) obj)));
                    } else if ("double".equals(name)) {
                        field.set(this, Double.valueOf(Double.parseDouble((String) obj)));
                    } else if ("short".equals(name)) {
                        field.set(this, Short.valueOf(Short.parseShort((String) obj)));
                    } else if ("byte".equals(name)) {
                        field.set(this, Byte.valueOf(Byte.parseByte((String) obj)));
                    } else if ("char".equals(name)) {
                        field.set(this, Character.valueOf(((String) obj).charAt(0)));
                    }
                }
            } catch (IllegalAccessException e) {
                clq.ˎ.ˊ(TAG, "processValueError Throwable:" + e.getMessage());
            }
        }
    }

    private Object valueFromJson(Class cls, Class cls2, Object obj) throws IllegalAccessException, IllegalArgumentException, InstantiationException, ClassNotFoundException, JSONException {
        if (cls.isPrimitive() || cls.equals(String.class) || cls.equals(JSONObject.class)) {
            return (Param.TYPE_FLOAT.equals(cls.getName()) && (obj instanceof Double)) ? Float.valueOf(((Double) obj).floatValue()) : obj;
        } else {
            if (List.class.isAssignableFrom(cls)) {
                return listFromJson(cls2, obj);
            }
            if (JsonBean.class.isAssignableFrom(cls)) {
                if (!cls.equals(JsonBean.class)) {
                    return jsonBeanFromJson(cls, obj);
                }
                throw new IllegalArgumentException("error type, type:" + cls);
            } else if (Map.class.isAssignableFrom(cls)) {
                return mapFromJson(cls2, obj);
            } else {
                throw new IllegalArgumentException("unsupport type, Type:" + cls);
            }
        }
    }

    private Object jsonBeanFromJson(Class cls, Object obj) throws InstantiationException, IllegalAccessException, ClassNotFoundException, IllegalArgumentException, JSONException {
        JsonBean jsonBean = (JsonBean) cls.newInstance();
        jsonBean.fromJson((JSONObject) obj);
        return jsonBean;
    }

    protected Object listFromJson(Class cls, Object obj) throws InstantiationException, IllegalAccessException, ClassNotFoundException, IllegalArgumentException, JSONException {
        if (cls == null) {
            throw new IllegalArgumentException("generic type is null");
        } else if (obj instanceof JSONArray) {
            List arrayList = new ArrayList();
            JSONArray jSONArray = (JSONArray) obj;
            for (int i = 0; i < jSONArray.length(); i++) {
                Object valueFromJson = valueFromJson(cls, null, jSONArray.get(i));
                if (valueFromJson != null) {
                    if (cls.equals(valueFromJson.getClass())) {
                        arrayList.add(valueFromJson);
                    } else {
                        clq.ˎ.ˊ(TAG, "listFromJson error, memberClass:" + cls + ", valueClass:" + valueFromJson.getClass());
                    }
                }
            }
            return arrayList;
        } else {
            throw new IllegalArgumentException("jsonobject is not JSONArray, jsonValue:" + obj);
        }
    }

    private Object mapFromJson(Class cls, Object obj) throws InstantiationException, IllegalAccessException, ClassNotFoundException, IllegalArgumentException, JSONException {
        if (cls == null) {
            throw new IllegalArgumentException("generic type is null");
        } else if (obj instanceof JSONObject) {
            Map linkedHashMap = new LinkedHashMap();
            JSONObject jSONObject = (JSONObject) obj;
            Iterator keys = jSONObject.keys();
            while (keys.hasNext()) {
                String str = (String) keys.next();
                Object valueFromJson = valueFromJson(cls, null, jSONObject.get(str));
                if (valueFromJson != null) {
                    if (cls.equals(valueFromJson.getClass())) {
                        linkedHashMap.put(str, valueFromJson);
                    } else {
                        clq.ˎ.ˊ(TAG, "mapFromJson error, memberClass:" + cls + ", valueClass:" + valueFromJson.getClass());
                    }
                }
            }
            return linkedHashMap;
        } else {
            throw new IllegalArgumentException("jsonobject is not JSONObject, jsonValue:" + obj);
        }
    }
}
